import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import {
    Box,
    Button,
    Card,
    CardContent,
    Typography,
    List,
    ListItem,
    ListItemText,
    IconButton,
    LinearProgress,
    TextField,
    Alert,
} from '@mui/material';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import DownloadIcon from '@mui/icons-material/Download';
import FolderIcon from '@mui/icons-material/Folder';

const MiniO = () => {
    const [files, setFiles] = useState([]);
    const [uploading, setUploading] = useState(false);
    const [uploadProgress, setUploadProgress] = useState(0);
    const [error, setError] = useState('');
    const fileInputRef = useRef(null);
    const [currentPath, setCurrentPath] = useState('');

    const username = 'my-data';

    // 获取文件列表
    const fetchFiles = async (user, path = '') => {
        try {
            const encodedPath = path ? encodeURIComponent(path) : '';
            console.log("encodedPath",encodedPath)
            const res = await axios.get(`http://localhost:8000/files/${user}/${encodedPath}`);

            // 安全提取数据，提供默认值
            const folders = Array.isArray(res.data.folders) ? res.data.folders : [];
            const filesData = Array.isArray(res.data.files) ? res.data.files : [];

            const items = [
                // 文件夹
                ...folders.map(f => ({
                    ...f,
                    isDir: true,
                    name: f.name?.replace(/\/$/, '') || 'unknown-folder' // 去掉末尾 /
                })),
                // 文件
                ...filesData.map(f => ({
                    ...f,
                    isDir: false,
                    name: f.original_path?.split('/').pop() || f.name || 'unknown-file'
                }))
            ];

            setFiles(items);
            setError('');
        } catch (err) {
            console.error('加载文件失败:', err);
            setError('加载失败: ' + (err.response?.data?.detail || err.message));
            setFiles([]); // 失败时清空或保持原状
        }
    };

    useEffect(() => {
        console.log('useEffect triggered', { username, currentPath });
        if (username) {
            fetchFiles(username, currentPath);
        }
    }, [username, currentPath]);

    // 上传文件
    const handleUpload = async (e) => {
        const file = e.target.files[0];
        if (!file || !username) return;

        const formData = new FormData();
        formData.append('username', username); // 👈 传用户名
        formData.append('file', file);

        try {
            setUploading(true);
            setUploadProgress(0);

            await axios.post('http://localhost:8000/upload/', formData, {
                headers: { 'Content-Type': 'multipart/form-data' },
                onUploadProgress: (progressEvent) => {
                    const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                    setUploadProgress(percent);
                },
            });

            alert(`上传成功！`);
            fetchFiles(username); // 刷新该用户的文件列表
        } catch (err) {
            alert('上传失败！');
        } finally {
            setUploading(false);
            e.target.value = null;
        }
    };

    // 上传文件夹
    const handleFolderUpload = async (e) => {
        const files = Array.from(e.target.files); // FileList → Array
        if (files.length === 0 || !username) return;

        for (let file of files) {
            const formData = new FormData();
            formData.append('username', username);

            // 构造带路径的文件名：project/src/index.js
            const filePath = file.webkitRelativePath || file.name; // 保留目录结构
            formData.append('file_path', filePath); // 把路径也传给后端
            formData.append('file', file);

            try {
                await axios.post('http://localhost:8000/upload-folder/', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' },
                });
            } catch (err) {
                console.error(`上传失败: ${filePath}`, err);
            }
        }

        alert('文件夹上传完成！');
        fetchFiles(username); // 刷新文件列表
    };

    // 下载文件
    // 下载函数
    const handleDownload = async (username, filename) => {
        try {
            const encodedFilename = encodeURIComponent(filename);
            const res = await axios.get(
                `http://localhost:8000/download/${username}/${encodedFilename}`,
                { responseType: 'blob' }
            );

            const url = window.URL.createObjectURL(new Blob([res.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
            link.remove();
        } catch (err) {
            alert('下载失败！');
        }
    };

    return (
        <Box sx={{ padding: 3, maxWidth: 800, margin: 'auto' }}>
            <Box sx={{ mb: 3 }}>
                <TextField
                    label="用户名"
                    value={username}
                    size="small"
                    sx={{ mr: 2, width: 200 }}
                />
            </Box>
            <Card>
                <CardContent>
                    <Typography variant="h4" component="h1" gutterBottom>
                        📁 MinIO 文件管理
                    </Typography>

                    {/* 上传区域 */}
                    <Box sx={{ mb: 3, textAlign: 'center' }}>
                        <label htmlFor="upload-button">
                            <input
                                accept="*/*"
                                style={{ display: 'none' }}
                                id="upload-button"
                                type="file"
                                onChange={handleUpload}
                                disabled={uploading}
                            />
                            <Button
                                variant="contained"
                                color="primary"
                                component="span"
                                startIcon={<CloudUploadIcon />}
                                disabled={uploading}
                            >
                                {uploading ? 'Uploading...' : '选择文件上传'}
                            </Button>
                        </label>

                        {uploading && (
                            <Box sx={{ mt: 2 }}>
                                <LinearProgress variant="determinate" value={uploadProgress} />
                                <Typography variant="body2" color="textSecondary">
                                    上传进度: {uploadProgress}%
                                </Typography>
                            </Box>
                        )}
                    </Box>
                    <Box sx={{ mb: 3, textAlign: 'center' }}>
                        <Button
                            variant="contained"
                            color="primary"
                            component="span"
                            startIcon={<CloudUploadIcon />}
                            onClick={() => fileInputRef.current.click()}
                            disabled={uploading}
                        >
                            选择文件夹上传
                        </Button>

                        <input
                            type="file"
                            ref={fileInputRef}
                            webkitdirectory=""
                            multiple
                            onChange={handleFolderUpload}
                            style={{ display: 'none' }}
                            disabled={uploading}
                        />

                        {uploading && (
                            <Box sx={{ mt: 2 }}>
                                <LinearProgress variant="determinate" value={uploadProgress} />
                                <Typography variant="body2" color="textSecondary">
                                    上传进度: {uploadProgress}%
                                </Typography>
                            </Box>
                        )}
                    </Box>

                    {/* 错误提示 */}
                    {error && (
                        <Alert severity="error" sx={{ mb: 2 }}>
                            {error}
                        </Alert>
                    )}

                    {/* 文件列表 */}
                    <Typography variant="h6" gutterBottom>
                        <FolderIcon /> 文件系统
                    </Typography>

                    {files.length === 0 ? (
                        <Typography color="textSecondary">暂无文件</Typography>
                    ) : (
                        <List>
                            {/* 返回上级按钮（如果不在根目录） */}
                            {currentPath && (
                                <ListItem
                                    button
                                    onClick={() => {
                                        const pathParts = currentPath.split('/');
                                        pathParts.pop();
                                        setCurrentPath(pathParts.join('/'));
                                    }}
                                >
                                    <ListItemText primary="⬅️ 返回上一级" />
                                </ListItem>
                            )}

                            {files.length === 0 ? (
                                <Typography color="textSecondary">此目录为空</Typography>
                            ) : (
                                files.map((item, index) => (
                                    <ListItem
                                        component={item.isDir ? "div" : "li"}  // 文件夹用 div 模拟按钮
                                        sx={{
                                            cursor: item.isDir ? 'pointer' : 'default',
                                            '&:hover': item.isDir ? { bgcolor: 'action.hover' } : {},
                                        }}
                                        onClick={() => {
                                            if (item.isDir) {
                                                const newPath = currentPath ? `${currentPath}/${item.name}` : item.name;
                                                setCurrentPath(newPath.replace(/\/+$/, ''));
                                            }
                                        }}
                                    >
                                        <ListItemText
                                            primary={
                                                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                                                    {item.isDir ? (
                                                        <FolderIcon fontSize="small" color="primary" />
                                                    ) : (
                                                        <Typography component="span">📄</Typography>
                                                    )}
                                                    <Typography component="span" sx={{ ml: 1 }}>
                                                        {item.name}
                                                    </Typography>
                                                </Box>
                                            }
                                            secondary={
                                                !item.isDir &&
                                                `大小: ${(item.size / 1024 / 1024).toFixed(2)} MB • 修改时间: ${new Date(item.last_modified).toLocaleString()}`
                                            }
                                        />
                                        {!item.isDir && (
                                            <IconButton
                                                edge="end"
                                                onClick={(e) => {
                                                    e.stopPropagation(); // 防止触发文件夹点击
                                                    handleDownload(username, item.original_path || item.name);
                                                }}
                                            >
                                                <DownloadIcon />
                                            </IconButton>
                                        )}
                                    </ListItem>
                                ))
                            )}
                        </List>
                    )}
                </CardContent>
            </Card>
        </Box>
    )
}

export default MiniO